package com.inossem.warehousestorage_inossem.activity.emergency_warehousing;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.inossem.loadandrefresh.PullToRefreshLayout;
import com.inossem.loadandrefresh.pullableview.PullableListView;
import com.inossem.utils.base.CameraUtils;
import com.inossem.utils.base.QRCodeUtils;
import com.inossem.utils.base.Utils;
import com.inossem.utils.constant.QRCodeConstant;
import com.inossem.utils.listener.NoDoubleClickListener;
import com.inossem.utils.log.LogUtils;
import com.inossem.utils.upload.UpLoadUtils;
import com.inossem.warehousestorage_inossem.R;
import com.inossem.warehousestorage_inossem.activity.base.BaseActivity;
import com.inossem.warehousestorage_inossem.activity.emergency_warehousing.extra.EmergencyWarehousingExtra;
import com.inossem.warehousestorage_inossem.adapter.emergencyWarehousing.ReceiveEmergencyWarehousingItemListAdapter;
import com.inossem.warehousestorage_inossem.bean.emergencyWarehousing.EmergencyWarehousingConfirmBean;
import com.inossem.warehousestorage_inossem.bean.emergencyWarehousing.EmergencyWarehousingReceiveOverviewBean;
import com.inossem.warehousestorage_inossem.constant.RequestConstant;
import com.inossem.warehousestorage_inossem.dialog.DialogUtils;
import com.inossem.warehousestorage_inossem.listener.GsonBeanListener;
import com.inossem.warehousestorage_inossem.manage.RequestManage;
import com.inossem.warehousestorage_inossem.request.emergencyWarehousing.EmergencyWarehousingReceiveOverviewRequest;
import com.inossem.warehousestorage_inossem.request.emergencyWarehousing.EmergencyWarehousingRemoveFileRequest;
import com.inossem.warehousestorage_inossem.utils.ActivityUtils;
import com.inossem.warehousestorage_inossem.utils.CompressUtils;
import com.inossem.warehousestorage_inossem.utils.EmergencyWarehousingUtils;
import com.inossem.warehousestorage_inossem.utils.SPUtils;
import com.yanzhenjie.nohttp.OnUploadListener;
import com.yanzhenjie.nohttp.rest.Response;
import com.yanzhenjie.nohttp.rest.SimpleResponseListener;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 作者：wsy on 2017/11/28 13:56
 * <p>
 * 邮箱：445979770@qq.com
 */

public class EmergenWarehousingReceiveOverviewActivity extends BaseActivity {

    private static final String SUCCESS = "0";//成功

    private TextView title, nextStep;

    private PullToRefreshLayout refresh;

    private PullableListView receiveEmergencyWarehousingtemList;

    private List<EmergencyWarehousingReceiveOverviewBean.DataBean.ItemListBean> allData;

    private ReceiveEmergencyWarehousingItemListAdapter adapter;

    private String mReceiptNumber, mMaterielCode ,filePath , mImageFileName , libraryStatusCode , emergencyTypeCode;

    private Map<String, String> headers;

    private List<EmergencyWarehousingReceiveOverviewBean.DataBean.FileListBean> localFileBean;

    private Bitmap bitmap;

    private int whats = UpLoadUtils.UPLOAD_IMAGE_REQUEST_CODE;

    private int isNew = 0;

    private long fileSize = 0;

    @Override
    protected void onCreateImpl(Bundle savedInstanceState) {
        setContentView(R.layout.activity_emergency_warehousing_receive_overview);
        initView(EmergenWarehousingReceiveOverviewActivity.this);
        SPUtils.removeReceiveEmergencyWarehousingInformation(EmergenWarehousingReceiveOverviewActivity.this);
    }

    @Override
    protected void onResumeImpl() {
        mMaterielCode = "";
        initData(EmergenWarehousingReceiveOverviewActivity.this);
    }

    private void initView(Activity activity) {
        title = (TextView) activity.findViewById(R.id.headerTitle);
        receiveEmergencyWarehousingtemList = (PullableListView) activity.findViewById(R.id.receiveEmergencyWarehousingItemList);
        refresh = (PullToRefreshLayout) activity.findViewById(R.id.receiveEmergencyWarehousingItemListRefresh);
        nextStep = (TextView) activity.findViewById(R.id.nextStep);
        headers = new HashMap<>();
        headers.put(RequestManage.HEADER_TOKEN, SPUtils.getToken(EmergenWarehousingReceiveOverviewActivity.this));
        localFileBean = new ArrayList<>();
    }

    private void initData(Activity activity) {
        title.setText(R.string.activity_emergency_warehousing_overview_title);
        ActivityUtils.initBackAndFunction(activity, R.string.activity_in_storage_receive_list_title_short, new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                finish();
            }
        });

        receiveEmergencyWarehousingtemList.setPullUpFlag(false);
        refresh.setOnRefreshListener(new PullToRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
                initData(activity);
                pullToRefreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
            }

            @Override
            public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
            }
        });
        nextStep.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                Intent intent = new Intent(activity, EmergencyWarehousingReceiveAddOperatorActivity.class);
                intent.putExtra(EmergencyWarehousingExtra.RECEIP_NUMBER, mReceiptNumber);
                intent.putExtra(EmergencyWarehousingExtra.STATUS_CODE, libraryStatusCode);
                intent.putExtra(EmergencyWarehousingExtra.EMERGENCT_TYPE_CODE, emergencyTypeCode);
                intent.putExtra(EmergencyWarehousingExtra.IS_NEW, isNew+"");
                startActivity(intent);
            }
        });
        getExtra(activity);
        getData(activity);
        setmScanListener((String scanResult, int length) -> {
            mMaterielCode = QRCodeUtils.DecryptQRCode(scanResult);
            getData(activity);
        }, QRCodeConstant.TYPE_MATERIEL_CODE);
    }

    private void getExtra(Activity activity) {
        mReceiptNumber = activity.getIntent().getStringExtra(EmergencyWarehousingExtra.RECEIP_NUMBER);
    }

    private void addEmergancyWarehousingReceiveItemListData(Context context, EmergencyWarehousingReceiveOverviewBean.DataBean bean, List<EmergencyWarehousingReceiveOverviewBean.DataBean.ItemListBean> receiveInStorageItemList, ListView listView, boolean flag) {
        if (flag) {
            adapter = new ReceiveEmergencyWarehousingItemListAdapter(context, bean, receiveInStorageItemList,localFileBean, mMaterielCode, new EmergenWarehousingReceiveOverviewActivity.EmergenWarehousingReceiveOverviewListener() {
                @Override
                public void onNoDoubleClickListener(String materielCode) {
                    mMaterielCode = materielCode;
                    getData(context);
                }

                @Override
                public void onDeleteImageClickListener(String uuid , boolean inLocal ,String mergencyType) {
                    if (inLocal) {
                        for (int i = 0; i < localFileBean.size(); i++) {
                            if (localFileBean.get(i).getFile_id().equals(uuid)) {
                                localFileBean.remove(i);
                            }
                        }
                        EmergencyWarehousingUtils.deleteFile(context , uuid);
                        getData(context);
                        isNew -= 1;
                    }else {
                        getDeleteRequest(context , mReceiptNumber , mergencyType , uuid  );
                    }
                }

                @Override
                public void onCameraClickListener() {
                    CameraUtils.openCameraReturnOriginal(EmergenWarehousingReceiveOverviewActivity.this, new CameraUtils.CameraResultInterface() {
                        @Override
                        public void returnIntent(Intent intent, int requestCode, String path ,String imageFileName) {
                            filePath = path;
                            mImageFileName = imageFileName;
                            startActivityForResult(intent, requestCode);
                        }
                    });
                }
            });
            listView.setAdapter(adapter);
        }
    }

    private String getTime () {
        return new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    }
    private void getData(Context context) {
        String receiveEmergencyWarehousingInformation = SPUtils.getReceiveEmergencyWarehousingInformation(context);
        if (TextUtils.isEmpty(receiveEmergencyWarehousingInformation)) {
            getEmergencyWarehousing(context);
        } else {
            Gson gson = new Gson();
            EmergencyWarehousingReceiveOverviewBean bean = gson.fromJson(receiveEmergencyWarehousingInformation, EmergencyWarehousingReceiveOverviewBean.class);
            if (TextUtils.isEmpty(mMaterielCode)) {
                allData = bean.getBody().getItem_list();
            } else {
                allData = EmergencyWarehousingUtils.getReceiveEmergencyWarehousingList(context, mMaterielCode);
            }
            addEmergancyWarehousingReceiveItemListData(context, bean.getBody(), ActivityUtils.getShowData(allData, 0), receiveEmergencyWarehousingtemList, true);
        }
    }

    private void getEmergencyWarehousing(Context context){
        SPUtils.removeReceiveEmergencyWarehousingInformation(EmergenWarehousingReceiveOverviewActivity.this);
        EmergencyWarehousingReceiveOverviewRequest.request(context, mReceiptNumber, new GsonBeanListener<EmergencyWarehousingReceiveOverviewBean>() {
            @Override
            public void onSuccess(EmergencyWarehousingReceiveOverviewBean bean) {
                Gson gson = new Gson();
                String json = gson.toJson(bean, EmergencyWarehousingReceiveOverviewBean.class);
                SPUtils.saveReceiveEmergencyWarehousingInformation(context, json);
                EmergencyWarehousingReceiveOverviewBean.DataBean data = bean.getBody();
                allData = bean.getBody().getItem_list();
                //暂时注释
                libraryStatusCode = bean.getBody().getStatus_code();
                emergencyTypeCode = bean.getBody().getReceipt_type();
                addEmergancyWarehousingReceiveItemListData(context, data, ActivityUtils.getShowData(allData, 0), receiveEmergencyWarehousingtemList, true);

            }
        });
    }

    private void getDeleteRequest (Context context ,String receiptNumber , String emergencyTypeCode , String uuid ) {
        EmergencyWarehousingRemoveFileRequest.request(context, EmergencyWarehousingUtils.getDeleteRequestBean(receiptNumber , emergencyTypeCode , uuid), new GsonBeanListener<EmergencyWarehousingConfirmBean>() {
            @Override
            public void onSuccess(EmergencyWarehousingConfirmBean bean) {
//                if (inLocal) {
//                    for (int i = 0; i < localFileBean.size(); i++) {
//                        if (localFileBean.get(i).getUuid().equals(uuid)) {
//                            localFileBean.remove(i);
//                        }
//                    }
//                }
                if (SUCCESS.equals(bean.getBody().getIs_success())) {
                    EmergencyWarehousingUtils.deleteFile(context , uuid);
                    getData(context);
                    Utils.middleToast(context, bean.getBody().getMessage());
                } else {
                    if (!TextUtils.isEmpty(bean.getBody().getMessage())) {
                        Utils.middleToast(context, bean.getBody().getMessage());
                    }
                }

            }
        });
    }
    private void upLoad () {
        File file = null;
        if (CompressUtils.compressImageToFileNormal(EmergenWarehousingReceiveOverviewActivity.this,new File(filePath)) != null) {
            file = CompressUtils.compressImageToFileNormal(EmergenWarehousingReceiveOverviewActivity.this,new File(filePath));
        }
        try {
            filePath = file.getCanonicalPath();
            LogUtils.i("file.getCanonicalPath() ==== " + file.getCanonicalPath());
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
             fileSize = CameraUtils.getFileSize(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Dialog loadingDialog = DialogUtils.getLoadingDialog(EmergenWarehousingReceiveOverviewActivity.this, null);
        UpLoadUtils.getInstance().request(whats, UpLoadUtils.getUploadRequest(whats,SPUtils.getFileServerUrl(EmergenWarehousingReceiveOverviewActivity.this) + RequestConstant.URL_EMERGENCY_WAREHOUSING_RUOLOAD , headers , file, new OnUploadListener() {
            @Override
            public void onStart(int what) {
//                Toast.makeText(QualityInspectionListActivity.this , "结束" ,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(int what) {
                loadingDialog.cancel();
//                Toast.makeText(EmergenWarehousingReceiveOverviewActivity.this , "取消" ,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onProgress(int what, int progress) {
//                mProgressBar.setProgress(progress);
            }

            @Override
            public void onFinish(int what) {
                loadingDialog.cancel();
//                Toast.makeText(EmergenWarehousingReceiveOverviewActivity.this , "结束" ,Toast.LENGTH_SHORT).show();
//
                whats += 1;
            }

            @Override
            public void onError(int what, Exception exception) {
                loadingDialog.cancel();
            }
        }), new SimpleResponseListener<String>() {
            @Override
            public void onSucceed(int what, Response<String> response) {
                super.onSucceed(what, response);
                Log.i("wang" , response.get());
                EmergencyWarehousingReceiveOverviewBean.DataBean.FileListBean bean = new EmergencyWarehousingReceiveOverviewBean.DataBean.FileListBean();
                bean.setFile_id(response.get());
                bean.setBitmapPath(filePath);
                LogUtils.i("filePath ======= " + filePath);
                bean.setExt("jpg");
                bean.setFile_name(mImageFileName);
                bean.setSize(fileSize + "");
                localFileBean.add(bean);
                isNew += 1;
                EmergencyWarehousingUtils.saveFileToSP(EmergenWarehousingReceiveOverviewActivity.this , bean);
                getData(EmergenWarehousingReceiveOverviewActivity.this);
            }

            @Override
            public void onFailed(int what, Response<String> response) {
                super.onFailed(what, response);
                Toast.makeText(EmergenWarehousingReceiveOverviewActivity.this , UpLoadUtils.getErroMessage(response.getException()) ,Toast.LENGTH_SHORT).show();
            }
        });
        loadingDialog.setCancelable(false);
        loadingDialog.show();
    }

    @Override
    protected void onActivityResultImpl(int requestCode, int resultCode, Intent data) {

        if (requestCode == CameraUtils.SMALL_PICTURE && resultCode == RESULT_OK) {
//            Bitmap imageBitmap = (Bitmap) data.getExtras().get("data");
//            smallImageView.setImageBitmap(imageBitmap);
        }else if (requestCode == CameraUtils.BIG_PICTURE && resultCode == RESULT_OK) {

//            bitmap = CameraUtils.uriToBitmap(filePath);
            upLoad();
        }
    }
    public interface EmergenWarehousingReceiveOverviewListener {
        void onNoDoubleClickListener(String materielCode);
        void onDeleteImageClickListener(String uuid , boolean inLocal , String mergencyType);
        void onCameraClickListener();
    }

    @Override
    public void onBackPressed() {
        DialogUtils.getConfirmDialog(EmergenWarehousingReceiveOverviewActivity.this, getResources().getString(R.string.activity_in_storage_receive_overview_clear_prompt), new DialogUtils.ConfirmDialogListener() {
            @Override
            public void onConfirm(Dialog dialog) {
                EmergenWarehousingReceiveOverviewActivity.super.onBackPressed();
            }
        }).show();
    }

    @Override
    protected void onDestroyImpl() {
        super.onDestroyImpl();
//        UpLoadUtils.getInstance().stop();
    }
}
